<template>
  <div class="fire-animation-layer">
    <ol-layer :map="map">
      <ol-vector-layer :style="fireStyle">
        <ol-source-vector :features="currentFeatures"/>
      </ol-vector-layer>
    </ol-layer>
  </div>
</template>

<script lang="ts">
import { Feature } from 'ol';
import { Point } from 'ol/geom';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';

@Component
export default class FireAnimationLayer extends Vue {
  @Prop() map!: any;
  @Prop() firePoints!: Array<any>;

  private currentFeatures: Feature[] = [];
  private animationFrame!: number;

  private fireStyle = {
    'circle-radius': ['interpolate', ['linear'], ['zoom'],
      10, 5,
      15, 10,
      20, 20
    ],
    'circle-color': [
      'interpolate',
      ['linear'],
      ['get', 'temperature'],
      300, '#ffd700',
      600, '#ffa500',
      900, '#ff4500',
      1200, '#ff0000'
    ],
    'circle-opacity': 0.7,
    'circle-stroke-width': 2,
    'circle-stroke-color': '#fff'
  };

  @Watch('firePoints')
  updateFeatures(newVal: any[]) {
    this.currentFeatures = newVal.map(point => {
      return new Feature({
        geometry: new Point(point.coordinates),
        temperature: point.temperature,
        radius: point.radius
      });
    });
    
    this.animateFire();
  }

  private animateFire() {
    cancelAnimationFrame(this.animationFrame);
    
    const animate = () => {
      this.currentFeatures.forEach(feature => {
        const style:any = feature.getStyle();
        const currentRadius = style.getImage().getRadius();
        style.getImage().setRadius(currentRadius * 0.95 + Math.random() * 2);
      });
      this.animationFrame = requestAnimationFrame(animate);
    };
    
    animate();
  }

  beforeDestroy() {
    cancelAnimationFrame(this.animationFrame);
  }
}
</script>